package com.yanqu.road.utils;

import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CsvHelper {
    /**
     * CSV文件生成方法
     *
     * @param head       文件头
     * @param dataList   数据列表
     * @param outPutPath 文件输出路径
     * @param filename   文件名
     * @return
     */
    public static File createCSVFile(List<Object> head, List<List<Object>> dataList, String outPutPath, String filename) {

        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv");
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            if (!csvFile.exists()) {
                csvFile.createNewFile();
            }

            // 使正确读取分隔符","
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                    csvFile), "UTF8"), 1024);
            // 写入文件头部
            writeRow(head, csvWtriter);

            // 写入文件内容
            for (List<Object> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据方法
     *
     * @param row
     * @param csvWriter
     * @throws IOException
     */
    private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }

    public static <T> File createCsv(Class<T> tClass, List<T> inputDataList, String outPath, String fileName) {
        List<Object> fieldNameList = new ArrayList<Object>();
        Field[] declaredFields = tClass.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            fieldNameList.add(field.getName());
        }
        List<List<Object>> excelDataList = new ArrayList<>();

        for (T inputData : inputDataList) {
            List<Object> data = new ArrayList<Object>();
            for (Field field : declaredFields) {
                try {
                    data.add(field.get(inputData));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }

            excelDataList.add(data);
        }

        File file = CsvHelper.createCSVFile(fieldNameList, excelDataList, outPath, fileName);
        return file;
    }
}
